package com.hunglv.transportalert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import com.hunglv.databasehelper.*;
import com.hunglv.entity.BusItem;
import com.hunglv.entity.StopItem;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

public class StopPickerActivity extends Activity implements
		OnItemSelectedListener, DialogInterface.OnClickListener,
		View.OnClickListener {
	// view control
	private ImageButton saveBtn;
	private Spinner bus_picker, stop_picker, sound_picker;
	private EditText name_editor;

	// database helper
	protected BusInfoDatabaseHelper myBusInfoDbHelper;
	private Cursor busInfoCursor;

	// binding data
	private ArrayList<BusItem> bus_list;
	private ArrayAdapter<BusItem> bus_list_adapter;

	private ArrayList<StopItem> bus_stop_list;
	private ArrayAdapter<StopItem> bus_stop_list_adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create);

		// get view
		saveBtn = (ImageButton) findViewById(R.id.save_btn);
		bus_picker = (Spinner) findViewById(R.id.bus_picker);
		stop_picker = (Spinner) findViewById(R.id.stop_picker);
		sound_picker = (Spinner) findViewById(R.id.sound_picker);
		name_editor = (EditText) findViewById(R.id.name_edittext);

		// initial default name
		name_editor.setText(R.string.default_alarm_name);

		// initial bus_list and bind to bus picker
		bus_list = new ArrayList<BusItem>();
		bus_list_adapter = new ArrayAdapter<BusItem>(this,
				android.R.layout.simple_spinner_item, bus_list);
		bus_list_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bus_picker.setAdapter(bus_list_adapter);

		// initial bus_stop_list and bind to stop picker
		bus_stop_list = new ArrayList<StopItem>();
		bus_stop_list_adapter = new ArrayAdapter<StopItem>(this,
				android.R.layout.simple_spinner_item, bus_stop_list);
		bus_stop_list_adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		stop_picker.setAdapter(bus_stop_list_adapter);

		// initial and load database
		myBusInfoDbHelper = new BusInfoDatabaseHelper(this);
		loadDatabase();

		// update bus list
		populateBusList();

		// trap selection event from picker
		bus_picker.setOnItemSelectedListener(this);
		stop_picker.setOnItemSelectedListener(this);
		sound_picker.setOnItemSelectedListener(this);

		// trap touch event from save_btn
		saveBtn.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_create, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		myBusInfoDbHelper.close();
	}

	private void loadDatabase() {
		try {
			myBusInfoDbHelper.createDatabase();
		} catch (IOException e) {
			throw new Error("Unable to create database");
		}

		try {
			myBusInfoDbHelper.openDatabase();
		} catch (SQLException e) {
			throw e;
		}
	}

	private void populateBusList() {
		busInfoCursor = myBusInfoDbHelper.getAllBusCursor();
		updateBusList();
	}

	private void updateBusList() {
		bus_list.clear();
		if (busInfoCursor.moveToFirst()) {
			do {
				String _id = busInfoCursor
						.getString(BusInfoDatabaseHelper.BUS_ID_COLUMN);
				String _name = busInfoCursor
						.getString(BusInfoDatabaseHelper.BUS_NAME_COLUMN);
				String _stop = busInfoCursor
						.getString(BusInfoDatabaseHelper.BUS_STOP_COLUMN);
				bus_list.add(0, new BusItem(_id, _name, _stop));
			} while (busInfoCursor.moveToNext());
			bus_list_adapter.notifyDataSetChanged();
		}
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	public void updateBusStopList(BusItem bus) {
		// erase all existed bus stop in bus_stop_list (renew bus_stop_list)
		bus_stop_list.clear();

		String bus_stop_str = bus.getStop();
		ArrayList<Integer> stops = splitBusStopData(bus_stop_str);
		for (Integer i : stops) {
			StopItem item = myBusInfoDbHelper.getStopItem(i);
			if (item != null) {
				bus_stop_list.add(item);
			}
		}

		bus_stop_list_adapter.notifyDataSetChanged();
	}

	private ArrayList<Integer> splitBusStopData(String data) {
		ArrayList<Integer> result = new ArrayList<Integer>();
		StringTokenizer st = new StringTokenizer(data, " ");
		while (st.hasMoreTokens()) {
			String sNode = st.nextToken();
			Integer iNode = Integer.valueOf(sNode);
			result.add(iNode);
		}
		return result;
	}

	private void updateAlarmLocationDatabase(StopItem item, boolean state) {
		if (state) {
			// insert new location to database
			long result = MainActivity.setAlarmLocationDbHelper
					.insertStopLocation(item);
			if (result > 0)
				Log.e("BusAlert", "set alarm successfully");
		} else {
			// remove location from database
			boolean result = MainActivity.setAlarmLocationDbHelper
					.removeStopLocation(item.getId());
			if (result) {
				Log.e("BusAlert", "remove alarm successfully");
			}
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case DialogInterface.BUTTON_POSITIVE:
			// "Yeah" button clicked
			startActivityForResult(new Intent(
					android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
					0);
			break;

		case DialogInterface.BUTTON_NEGATIVE:
			// "No" button clicked
			break;
		}
	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.bus_picker:
			Object item = parent.getItemAtPosition(position);
			if (item instanceof BusItem) {
				updateBusStopList((BusItem) item);
			}
			break;
		case R.id.stop_picker:
			break;
		case R.id.sound_picker:
			break;
		}

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.save_btn) {
			GpsLoader mGpsLoader = new GpsLoader(StopPickerActivity.this);
			if (!mGpsLoader.isLocationProvided()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						StopPickerActivity.this);
				builder.setMessage(R.string.turn_on_gps_promt);
				builder.setPositiveButton(MainActivity.mResources
						.getString(R.string.gps_setting_prompt),
						StopPickerActivity.this);
				builder.setNeutralButton(MainActivity.mResources
						.getString(R.string.wifi_setting_prompt), this);
				builder.setNegativeButton(MainActivity.mResources
						.getString(R.string.cancel_prompt),
						StopPickerActivity.this);
				builder.show();
			} else {
				try {
					StopItem item = (StopItem) stop_picker.getSelectedItem();
					updateAlarmLocationDatabase(item, true);
					Intent intent = new Intent(StopPickerActivity.this,
							MainActivity.class);
					startActivity(intent);
				} catch (ClassCastException ex) {

				}
			}
		}
	}
}
